<template>
	<div class="all-courses">
		<div class="search-bar">
			<a-row :gutter="16">
				<a-col :span="8">
					<a-input-search placeholder="按课程名称、教师搜索" @search="handleSearch" enterButton v-model="searchValue" />
				</a-col>
				<a-col :span="8">
					<a-select style="width: 100%" placeholder="按课程类型筛选" @change="handleTypeChange" v-model="filterType">
						<a-select-option value="all">全部课程</a-select-option>
						<a-select-option value="required">必修课</a-select-option>
						<a-select-option value="elective">选修课</a-select-option>
						<a-select-option value="public">公选课</a-select-option>
					</a-select>
				</a-col>
				<a-col :span="8">
					<a-button @click="refresh" style="float: right;">
						<a-icon type="sync" />刷新
					</a-button>
				</a-col>
			</a-row>
		</div>

		<a-table :columns="columns" :dataSource="filteredCourses" rowKey="id" :pagination="pagination"
			:loading="loading">
			<span slot="timeLocation" slot-scope="text, record">
				<div>{{ record.time }}</div>
				<div>{{ record.location }}</div>
			</span>

			<span slot="enrollment" slot-scope="text, record">
				{{ record.enrolled }}/{{ record.capacity }}
				<a-progress :percent="Math.round((record.enrolled / record.capacity) * 100)"
					:status="getProgressStatus(record)" size="small" />
			</span>

			<span slot="action" slot-scope="text, record">
				<a-button type="primary" size="small" @click="handleSelect(record)" :disabled="!canSelect(record)">
					选择
				</a-button>
				<a-tooltip v-if="!canSelect(record)" :title="getDisabledReason(record)">
					<a-icon type="question-circle" style="margin-left: 8px" />
				</a-tooltip>
			</span>
		</a-table>
	</div>
</template>

<script>
	// 真实课程数据
	const REAL_COURSES = [{
			id: 'CS101',
			name: '计算机科学导论',
			credit: 3,
			teacher: '李红梅',
			time: 'Mon-1,2',
			location: '理科楼201',
			enrolled: 45,
			capacity: 60,
			type: 'required',
			requirePrerequisite: false
		},
		{
			id: 'CS301',
			name: '数据结构与算法',
			credit: 4,
			teacher: '李红梅',
			time: 'Mon-3,4',
			location: '理科楼202',
			enrolled: 38,
			capacity: 45,
			type: 'required',
			requirePrerequisite: true,
			prerequisite: 'CS101'
		}
	];

	const columns = [{
			title: '课程编号',
			dataIndex: 'id',
			key: 'id',
			width: 100,
			sorter: true
		},
		{
			title: '课程名称',
			dataIndex: 'name',
			key: 'name',
			width: 150,
			sorter: true
		},
		{
			title: '学分',
			dataIndex: 'credit',
			key: 'credit',
			width: 80,
			sorter: true
		},
		{
			title: '任课教师',
			dataIndex: 'teacher',
			key: 'teacher',
			width: 120,
			sorter: true
		},
		{
			title: '时间/地点',
			key: "timeLocation",
			scopedSlots: {
				customRender: 'timeLocation'
			},
			width: 180
		},
		{
			title: '选课人数',
			key: 'enrollment',
			scopedSlots: {
				customRender: 'enrollment'
			},
			width: 150
		},
		{
			title: '课程类型',
			dataIndex: 'type',
			key: 'type',
			width: 100,
			customRender: (text) => {
				const typeMap = {
					'required': '必修',
					'elective': '选修',
					'public': '公选'
				};
				return typeMap[text] || text;
			}
		},
		{
			title: '操作',
			key: 'action',
			scopedSlots: {
				customRender: 'action'
			},
			width: 120
		}
	];

	export default {
		data() {
			return {
				columns,
			  filteredCourses: [],
			  loading: false,
			  searchValue: '',
			  filterType: 'all',
			  pagination: {
				current: 1,
				pageSize: 10,
				total: 0,
				showSizeChanger: true,
				pageSizeOptions: ['10', '20', '50'],
				showTotal: total => `共 ${total} 门课程`
			  },
			  courses: REAL_COURSES,
			  selectedCourses: []
			};
		},
		created() {
			this.filterCourses();
		},
		methods: {
			handleTableChange(pagination, filters, sorter) {
			      this.pagination.current = pagination.current;
			      this.pagination.pageSize = pagination.pageSize;
			      this.filterCourses();
			    },
			formatTime(timeStr) {
				const dayMap = {
					'Mon': '周一',
					'Tue': '周二',
					'Wed': '周三',
					'Thu': '周四',
					'Fri': '周五'
				};
				const [day, periods] = timeStr.split('-');
				return `${dayMap[day] || day} 第${periods.split(',').join(',')}节`;
			},
			filterCourses() {
				let filtered = this.courses;

				// 按搜索条件过滤
				if (this.searchValue) {
					const lowerSearch = this.searchValue.toLowerCase();
					filtered = filtered.filter(c =>
						c.name.toLowerCase().includes(lowerSearch) ||
						c.teacher.toLowerCase().includes(lowerSearch)
					);
				}

				// 按类型过滤
				if (this.filterType !== 'all') {
					filtered = filtered.filter(c => c.type === this.filterType);
				}

				this.filteredCourses = filtered;
				this.pagination.total = filtered.length;
			},

			handleSearch(value) {
				this.searchValue = value;
				this.filterCourses();
			},

			handleTypeChange(value) {
				this.filterType = value;
				this.filterCourses();
			},

			refresh() {
				this.loading = true;
				setTimeout(() => {
					this.filterCourses();
					this.loading = false;
				}, 500);
			},

			canSelect(course) {
				// 检查是否可以选择该课程
				// 1. 检查是否已选
				if (this.selectedCourses.some(c => c.id === course.id)) {
					return false;
				}

				// 2. 检查时间冲突
				const hasConflict = this.selectedCourses.some(selected => {
					return selected.time === course.time;
				});
				if (hasConflict) {
					return false;
				}

				// 3. 检查先修课程要求
				if (course.requirePrerequisite) {
					// 这里应该检查学生是否已完成先修课程
					return false;
				}

				return true;
			},

			getDisabledReason(course) {
				if (this.selectedCourses.some(c => c.id === course.id)) {
					return '您已选择该课程';
				}

				const hasConflict = this.selectedCourses.some(selected => {
					return selected.time === course.time;
				});
				if (hasConflict) {
					return '时间冲突';
				}

				if (course.requirePrerequisite) {
					return `需要先修课程: ${course.prerequisite}`;
				}

				return '不可选';
			},

			getProgressStatus(course) {
				const percent = (course.enrolled / course.capacity) * 100;
				if (percent >= 90) {
					return 'exception';
				} else if (percent >= 70) {
					return 'active';
				}
				return 'normal';
			},

			handleSelect(course) {
				this.$confirm({
					title: '确认选择该课程吗?',
					content: `课程名称: ${course.name}\n任课教师: ${course.teacher}\n上课时间: ${course.time}`,
					onOk: () => {
						// 1. 更新已选课程列表
						this.selectedCourses.push(course);

						// 2. 更新课程的已选人数
						const courseIndex = this.courses.findIndex(c => c.id === course.id);
						if (courseIndex !== -1) {
							// 使用Vue.set或直接赋值确保响应式更新
							this.$set(this.courses, courseIndex, {
								...this.courses[courseIndex],
								enrolled: this.courses[courseIndex].enrolled + 1
							});
						}

						// 3. 显示成功消息

						// 4. 触发事件(如果有需要)
						this.$emit('select', course);

						// 注意：如果使用计算属性filteredCourses，这里不需要手动调用filterCourses()
					},
					onCancel() {}
				});
			},
		}
	};
</script>

<style scoped>
	.all-courses {
		padding: 20px;
		padding-top: 0;
	}

	.search-bar {
		margin-bottom: 16px;
	}
</style>